//
//  BookManagerView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 03.04.25.
//

import SwiftUI

struct BookManagerView: View {
    
    @Environment(\.presentationMode) var presentationMode
    
    @EnvironmentObject var bookSelection: BookSelection
    
    @Environment(\.presentToast) var presentToast
    
    @State private var navigationToAddBook = false
    @State private var navigationToEditBook = false
    @State private var navigationToSortBook = false
    @State private var navigationToArchiveBook = false
    @State private var showMoreSheet = false
    @State private var showBookManagerMore = false
    @State private var showBookArchiveSheet = false
    @State private var showActionSheet = false
    @State private var actionSheetType: BookActionSheetType = .mangerMore
    @State private var actionClickBook: AccountingBook? = nil
    
    @StateObject var viewModel = BookManagerViewModel()
    
    var body: some View {
        ZStack {
            VStack {
                List {
                    ForEach($viewModel.books.indices, id:\.self) { index in
                        let book = viewModel.books[index]
                        Button(action: {
                            BookManager.standard.setCurrentBook(book: book)
                            bookSelection.currentBook = viewModel.books[index]
                            presentationMode.wrappedValue.dismiss()
                        }) {
                            BookItemView(book: book, isSelected: book == bookSelection.currentBook, viewType: .more, onMoreClick: {
                                actionClickBook = book
                                showMoreSheet = true
                            })
                            .padding(EdgeInsets(top: 20, leading: 16, bottom: 20, trailing: 16))
                            .background(Color.koiColorBackgroundItem)
                            .cornerRadius(16)
                            .padding(.vertical, 5)
                        }
                        .listRowSeparator(.hidden)
                        .listRowInsets(EdgeInsets())
                        .listRowBackground(Color.clear)
                        .actionSheet(isPresented: $showMoreSheet, content: {
                            ActionSheet(title: Text(""), buttons: [
                                .default(Text("编辑账本")) {
                                    navigationToEditBook = true
                                },
                                .default(Text("归档账本")) {
                                    actionSheetType = .archive
                                    showActionSheet = true
                                },
                                .default(Text("删除账本")) {
                                    actionSheetType = .delete
                                    showActionSheet = true
                                },
                                .cancel(Text("取消"))
                            ])
                        })
                    }
                }
                .listStyle(.plain)
                .padding(EdgeInsets(top: 0, leading: 20, bottom: 0, trailing:20)) // 去除边距
                .ignoresSafeArea(.container, edges: .bottom)
            }
            
            VStack {
                Spacer()
                Button(action: {
                    // 新增账本
                     navigationToAddBook = true
                }) {
                    Text("新增账本")
                        .font(.system(size: 15))
                        .bold()
                        .foregroundColor(Color.white)
                        .padding(EdgeInsets(top: 15, leading: 45, bottom: 15, trailing: 45))
                        .background(Color.koiColorPrimary)
                        .cornerRadius(40)
                }.padding(.bottom, 45)
            }
        }
        .navigationBarItems(trailing: Button(action: {
            // 显示更多操作
            actionSheetType = .mangerMore
            showActionSheet = true
        }) { Image("koi_ic_more_horiz") })
        .navigationDestination(isPresented: $navigationToAddBook, destination: { AddBookView() })
        .navigationDestination(isPresented: $navigationToSortBook, destination: { BookSortView() })
        .navigationDestination(isPresented: $navigationToArchiveBook, destination: { BookArchiveView() })
        .actionSheet(isPresented: $showActionSheet, content: {
            switch actionSheetType {
            case .mangerMore:
                ActionSheet(title: Text(""), buttons: [
                    .default(Text("账本排序")) {
                        navigationToSortBook = true
                    },
                    .default(Text("查看归档账本")) {
                        navigationToArchiveBook = true
                    },
                    .cancel(Text("取消"))
                ])
            case .archive:
                ActionSheet(
                    title: Text("确定要归档这个账本吗？"),
                    message: Text("归档账本后，此账本将不再账本管理界面和首页显示，但账本中的数据并没有消失，在统计中依然会显示此账本中的数据"),
                    buttons: [
                        .destructive(Text("确认归档")) {
                            viewModel.archive(book: actionClickBook)
                        },
                        .cancel(Text("取消"))
                    ])
            case .delete:
                ActionSheet(title: Text("确认删除账本「\(String(describing: actionClickBook!.bookName))」和账本下所有记账数据吗？"),buttons: [
                    .destructive(Text("确认删除")) {
                        // TODO 如果删除的是当前选中账本，删除账本之后当前选中账本切换到默认账本
                        viewModel.delete(book: actionClickBook)
                    },
                    .cancel(Text("取消"))
                ])
            }
        })
        .onChange(of: viewModel.archiveState) { newValue in
            if (newValue == "success") {
                viewModel.archiveState = ""
                presentToast(.init(message: "账本归档成功"))
                viewModel.loadBooks()
            }
        }
        .onChange(of: viewModel.deleteState) { newValue in
            if (newValue == "success") {
                viewModel.deleteState = ""
                // 如果删除的是当前选中的账本，当前账本切换到默认账本
                if (actionClickBook == bookSelection.currentBook) {
                    let defaultBook = viewModel.books.filter{ (item) in item.isDefaultBook()}.first ?? BookManager.standard.defaultBook()
                    bookSelection.currentBook = defaultBook
                    BookManager.standard.setCurrentBook(book: defaultBook)
                }
                presentToast(.init(message: "账本删除成功"))
                viewModel.loadBooks()
            }
        }
        .onAppear{
            viewModel.loadBooks()
        }
        .koiToolbar(title: Text("账本管理"))
        .background(Color.koiColorBackground)
    }
}

enum BookActionSheetType {
    case mangerMore, archive, delete
}

@available(iOS 18.0, *)
#Preview {
    let bookSelection = BookSelection()
    BookManagerView().environmentObject(bookSelection)
}
